<template>
  <el-row >
    <el-col :xs="10" :sm="8" :md="6" :lg="4" :xl="2" style="overflow: hidden;">
      <div style="padding: 10px;">
        <!-- <div  style="padding-bottom: 10px;text-align: right;">

          <el-tag style="overflow: hidden;"  :closable="company_id.length > 0?true:false" @close="removeCompany">
            {{ targetName }}-{{ company_id }}
          </el-tag>
        </div> -->
        <div style="padding: 10px;background: #fff;">
          <el-tree default-expand-all 
           ref="treeRef"
        style="height: calc(100vh - 100px);overflow-y: auto;overflow-x: hidden;" 
        node-key="id"
        highlight-current
         :current-node-key="currentKey"
        :data="companyTree" 
        :expand-on-click-node="false"
        :props="{ label: 'name', value: 'id' }"
        @node-click="handleNodeClick" />
        </div>
     </div>
    </el-col>
    <el-col :xs="14" :sm="16" :md="18" :lg="20" :xl="22" >
      <div style="padding: 10px 10px 0px 0px;">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="lodingForm.form.name" placeholder="请输入账号、姓名、电话" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="lodingForm.form.status" clearable placeholder="用户状态" style="width:120px">
            <el-option v-for="item in proxy.$statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSerch" circle ><el-icon><Search /></el-icon></el-button>
        
          <el-button type="success" @click="onLoding"  >刷新</el-button>
       
          <el-button  @click="handleClickAdd" type="primary" plain ><el-icon><Plus /></el-icon>添加</el-button >
        </el-form-item>
      </el-form>
      <el-table row-key="id" empty-text="暂无数据" v-loading="lodingForm.loading"  @sort-change="sortChange" :data="tableData" default-expand-all style="width: 100%;height: calc(100vh - 182px);" border>
        <el-table-column fixed type="index" label="序号" min-width="55"></el-table-column>
        <el-table-column prop="id" label="id"   fixed />
        <el-table-column prop="username" label="账号" min-width="120" show-overflow-tooltip sortable="custom"  />
        <el-table-column prop="name" label="姓名" show-overflow-tooltip sortable="custom"  align="center" />
        <el-table-column prop="phone" label="电话" min-width="120" show-overflow-tooltip sortable="custom"  align="center" />
        <el-table-column prop="company_id" label="所属单位" show-overflow-tooltip sortable="custom"  min-width="180" >
          <template #default="scope">
            {{ scope.row.company_list? scope.row.company_list.name : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="role_ids" label="所属角色"  sortable="custom"  min-width="120" >
          <template #default="scope" >
            <template v-if="scope.row.role_ids !== null">
              <template v-for="role in roleData">
                <template v-for="item in JSON.parse(scope.row.role_ids)">
                 <el-tag style="margin-right: 10px;" size="small"  v-if="item === role.id" :key="item">{{ role.name }}</el-tag>
                </template>
              </template>
            </template>
            
          </template>
        </el-table-column>
       
        <el-table-column prop="type" label="用户类型" sortable="custom" style="min-width: 120px;"  align="center" >
          <template #default="scope">
            <template v-for="item in proxy.$userTypeOptions">
              <el-tag :type="item.type"  size="small" v-if="item.value === scope.row.type">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" sortable="custom"   align="center" >
          <template #default="scope">
            <template v-for="item in proxy.$sexOptions">
              <el-tag :type="item.type" size="small" v-if="item.value === scope.row.sex">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" sortable="custom"  align="center" />
        <el-table-column label="状态" min-width="120" prop="status"  sortable="custom"  align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @change="onStatus(scope.row.id)" >
            <template #active-action>
              <span class="custom-active-action">启</span>
            </template>
            <template #inactive-action>
              <span class="custom-inactive-action">禁</span>
            </template>
          </el-switch>
        </template>
        
      </el-table-column>
      <el-table-column label="添加时间" min-width="190" prop="created_at"  sortable="created_at"  align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" min-width="140">
          <template #default="scope">
            <el-button type="primary" link class="button-edit" 
            size="small" @click="handleClickInfo(scope.row.id)">
            查看
          </el-button>
          <el-button type="success" link class="button-edit" 
            size="small" @click="handleClickEdit(scope.row.id)">
            修改
          </el-button>
            <el-popconfirm
              width="220"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确认删除该数据?"
              @confirm="onConfirm(scope.row.id)"
            >
              <template #reference>
                <el-button size="small"  type="danger" link >删除</el-button>
              </template>

              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">否</el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="confirm"
                >
                  是
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination" v-model:current-page="lodingForm.form.page" v-model:page-size="lodingForm.form.limit"
        :page-sizes="[10,50,100, 200, 300, 400]" :background="true" :size="size" 
        layout="total, sizes, prev, pager, next, jumper" :total="lodingForm.data.total"
         @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
        />
      </div>
     
    </el-col>
  </el-row>
  

  <el-dialog v-model="formDialog.show" :title="formDialog.title"  width="80%" align-center draggable>
    <formView  v-if="formDialog.show" :type="formDialog.type" :id="formDialog.id" @close-dialog="closeDialog"/>
  </el-dialog>


</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import { companyApi } from '@/utils/api/company';
import { userApi } from '@/utils/api/admin';
import { roleApi } from '@/utils/api/role';
import { ElTree } from 'element-plus'
import formView from './create.vue'
import { ElMessage } from 'element-plus'
import { jsx } from 'vue/jsx-runtime';
const route = useRoute();

const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
interface Tree {
  label: string
  children?: Tree[]
}
const currentKey = ref(null)
const treeRef = ref(null)
const handleNodeClick = (data: Tree) => {
  if(lodingForm.form.company_id !== data.id){
    lodingForm.form.company_id = data.id
    lodingForm.form.page = 1
    treeRef.value.setCheckedKeys([data.id])
    currentKey.value = data.id;
  }else{
    lodingForm.form.company_id = null
    lodingForm.form.page = 1
    currentKey.value = null;
  }
  getList()
}

const companyTree: Tree[] = reactive([])

const onLoding = () => {
  lodingForm.form.page = 1
  lodingForm.form.limit = 10
  lodingForm.form.name = ''
  lodingForm.form.status = null
  lodingForm.form.sortBy = {}
  getList()
}
const onSerch = () => {
  lodingForm.form.page = 1
  getList()

}


const size = ref<ComponentSize>('default')

const sortChange = ({ column, prop, order }) => {
  lodingForm.form.sortBy = {};
  // 处理排序逻辑
  if (order === 'ascending') {
    order = 'asc'
    // getList();
  } else if (order === 'descending') {
    order = 'desc'
  } else {
    // 重置排序或进行其他操作
  }
  Object.assign(lodingForm.form.sortBy, {[prop]:order});
  getList();
      
}
const convertToTree = (data: any[]): Tree[] => {
  const tree = [];
  const map = {};

  // 第一步：创建一个以 id 为键的映射表
  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // 第二步：找出所有可能的父节点 id
  const allParentIds = new Set(data.map(item => item.pid));

  // 第三步：构建树形结构
  data.forEach(item => {
    if (!map[item.pid]) {
      // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
      tree.push(map[item.id]);
    } else {
      // 否则，找到其父节点并将其添加到父节点的 children 数组中
      const parent = map[item.pid];
      if (parent) {
        parent.children.push(map[item.id]);
      }
    }
  });

  return tree;
}

const lodingForm = reactive({
 form:{
  name: '',
  company_id: null,
  status: null,
  page: 1,
  limit: 10,
  sortBy:{}
 },
 loading:false,
 data:{
  data:[],
  last_page: 0,
  limit: 0,
  page: 0,
  total: 0,
 }
})
const tableData = ref([])
const getList = async () => {
  lodingForm.loading = true
  // tableData.value  = []
  const res = await userApi.getlist(lodingForm.form)
  if(res.code === 200){
    lodingForm.data = res.data
    tableData.value = res.data.data
    tableData.value.forEach((item:any) => {
      item.status = item.status === 1 ? true : false
    })
  }else{
    tableData.value  = []
    ElMessage({
      type: res.type,
      message: res.message,
    })
  }
  lodingForm.loading = false 

}

const formDialog = reactive({
  show: false,
  id: null,
  type: 'add', 
})
const handleClickAdd = () => {
  formDialog.show = true
  formDialog.id = null
  formDialog.type = 'add'
  formDialog.title = '添加用户'
  // router.push({ name: 'companyCreate', params: { id: 0 } })
}
const closeDialog = () => {
  formDialog.show = false
  getList()
}
const handleClickInfo = (id: number) => {
  // router.push({ name: 'companyInfo', params: { id: id } })
  formDialog.show = true
  formDialog.title = '用户详情'
  formDialog.id = id
  formDialog.type = 'info'
}

const handleClickEdit = (id: number) => {
  formDialog.show = true
  formDialog.title = '修改用户'
  formDialog.id = id
  formDialog.type = 'edit'
  // router.push({ name: 'companyCreate', params: { id: id } })
}


const handleSizeChange = (val: number) => {
  lodingForm.form.page = 1
  lodingForm.form.limit = val
  getList()
}
const handleCurrentChange = (val: number) => {
  lodingForm.form.page = val

  getList()
}


//删除数据
const onConfirm = async (id: number) => {
  lodingForm.loading = true
  await userApi.delete({id:id})
  getList() 
}
//状态修改
const onStatus = async (id: number) => {
  lodingForm.loading = true
  await userApi.status({id:id})
  getList() 
}
const roleData = ref([])
const oldCompanyData = ref([])
onMounted(  async() => {
 const res = await companyApi.getAll()
 Object.assign(companyTree,convertToTree(res.data))
 getList()

 const res2 = await roleApi.getAll()
 roleData.value = res2.data


})


</script>

<style scoped>
.demo-form-inline {
  padding-bottom: 0;
}

.content {
  padding: 0;
  display: grid;
  grid-template-columns: auto 1fr; /* 第一列宽度随内容变化，第二列宽度自动填充 */

}

.leftCompany {
}

.rigthUser {
  width: 100%;
}

</style>
<style>
.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{

  /* background-color:#409eff ;  */
  background: none !important;
  color: #409eff;
}
</style>
